package org.akomantoso.core.io.util;

import java.io.IOException;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

import org.akomantoso.core.data.BasicoptElement;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.InputConstants;
import org.akomantoso.core.io.util.group.BasicContainersGroup;
import org.akomantoso.core.io.util.group.BlockElementsGroup;
import org.akomantoso.core.util.MapUtil;

public class BasicoptElementUtil {

	private BasicoptElementUtil() {
	}

	static final Map<String, Instantiator<BasicoptElement>> MAP = new IdentityHashMap<String, Instantiator<BasicoptElement>>();
	
	
	private static BasicoptElement instantiate(String elementName) {
		
		final Instantiator<? extends BasicoptElement> instatiator = MAP.get(elementName);
		if (instatiator == null) {
			throw new RuntimeException("Tag [" + elementName + "] not supported for BasicoptElement ?!?");
		}
		return instatiator.instantiate();
		
	}

	public static void read(Input in,List<BasicoptElement> elements) throws IOException {
		final String localName = in.getLocalName();
		BasicoptElement element = null;
		int eventType = in.readNext();
		while(true) {
			switch (eventType) {
			case InputConstants.START_ELEMENT:
				elements.add(element = instantiate(in.getLocalName()));
				element.readExternal(in);
				break;			
			case InputConstants.END_ELEMENT:
				if (localName == in.getLocalName()) {
					return;
				} 
			}
			eventType = in.readNext();
		}
	}
	
	static {
		MapUtil.copy(BlockElementsGroup.MAP, MAP);
		MapUtil.copy(BasicContainersGroup.MAP, MAP);
	}
	
	
}